<template>
  <div style="max-width:800px;margin:24px auto">
    <el-card>
      <el-form @submit.native.prevent="submit">
        <el-form-item label="标题">
          <el-input v-model="title" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="tags" multiple filterable allow-create default-first-option placeholder="选择或输入标签">
            <el-option v-for="t in hotTags" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="正文">
          <el-input type="textarea" :rows="8" v-model="content" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload action="/api/oss/image" list-type="picture-card" :on-success="onUploaded" :file-list="fileList" :on-remove="onRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-button type="primary" @click="submit">发布</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return { title: '', content: '', tags: [], images: [], fileList: [], hotTags: ['家常菜', '甜点', '早餐', '川菜', '面食'] }
  },
  methods: {
    onUploaded (res, file) {
      if (res.code === 1) {
        this.images.push(res.data.url)
      }
    },
    onRemove (file) {
      // 简化：根据 url 删除
      const url = file.response?.data?.url || file.url
      this.images = this.images.filter(u => u !== url)
    },
    async submit () {
      const token = localStorage.getItem('token')
      if (!token) { this.$message.error('请先登录'); this.$router.push('/login'); return }
      const { data } = await axios.post('/api/post/create', { title: this.title, content: this.content, tags: this.tags, images: this.images })
      if (data.code === 1) {
        this.$message.success('发布成功')
        this.$router.replace('/post/' + data.data.postId)
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
